const dayjs = require('dayjs')

const Controller = require('egg').Controller

class BillController extends Controller {
  async add() {
    const { ctx, app } = this
    const {
      amount,
      type_id,
      type_name,
      date,
      pay_type,
      remark = '',
    } = ctx.request.body
    if (!amount || !type_id || !type_name || !date || !pay_type) {
      ctx.body = {
        code: 400,
        msg: '参数错误',
        data: null,
      }
    }

    try {
      let user_id

      const token = ctx.request.header.authorization

      const decode = await app.jwt.verify(token, app.config.jwt.secret)

      if (!decode) return
      user_id = decode.id

      const result = await ctx.service.bill.add({
        amount,
        type_id,
        type_name,
        date,
        pay_type,
        remark,
        user_id,
      })

      ctx.body = {
        code: 200,
        msg: '请求成功',
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      }
    }
  }

  async list() {
    const { ctx, app } = this
    const { date, page = 1, page_size = 5, type_id = 'all' } = ctx.query
    try {
      let user_id
      const token = ctx.request.header.authorization
      const decode = await app.jwt.verify(token, app.config.jwt.secret)
      if (!decode) return

      user_id = decode.id
      console.log('type_id', type_id)

      const list = await ctx.service.bill.list(user_id)
      console.log(list.length, 222222)

      const _list = list.filter((item) => {
        console.log(dayjs(item.date).format('YYYY-MM'))
        console.log(date)
        if (type_id != 'all') {
          return (
            dayjs(item.date).format('YYYY-MM') == date &&
            type_id == item.type_id
          )
        }
        return dayjs(item.date).format('YYYY-MM') == date
      })
      console.log(_list.length, 1111111)

      const listMap = _list
        .reduce((curr, item) => {
          const date = dayjs(Number(item.date)).format('YYYY-MM-DD')
          // 如果能在累加的数组中找到当前项日期 date，那么在数组中的加入当前项到 bills 数组。
          if (
            curr &&
            curr.length &&
            curr.findIndex((item) => item.date == date) > -1
          ) {
            const index = curr.findIndex((item) => item.date == date)
            curr[index].bills.push(item)
          }
          // 如果在累加的数组中找不到当前项日期的，那么再新建一项。
          if (
            curr &&
            curr.length &&
            curr.findIndex((item) => item.date == date) == -1
          ) {
            curr.push({
              date,
              bills: [item],
            })
          }
          if (!curr.length) {
            curr.push({
              date,
              bills: [item],
            })
          }

          return curr
        }, [])
        .sort((a, b) => dayjs(b.date) - dayjs(a.date))
      console.log(listMap)

      const filterListMap = listMap.slice(
        (page - 1) * page_size,
        page * page_size,
      )

      let __list = list.filter(
        (item) => dayjs(Number(item.date)).format('YYYY-MM') == date,
      )

      let totalExpense = __list.reduce((curr, item) => {
        if (item.pay_type == 1) {
          curr += Number(item.amount)
          return curr
        }
        return curr
      }, 0)

      let totalIncome = __list.reduce((curr, item) => {
        if (item.pay_type == 2) {
          curr += Number(item.amount)
          return curr
        }
        return curr
      }, 0)
      console.log(123)
      ctx.body = {
        code: 200,
        msg: '请求成功',
        data: {
          totalExpense,
          totalIncome,
          totalPage: Math.ceil(listMap.length / page_size),
          list: filterListMap || [],
        },
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      }
    }
  }

  async detail() {
    const { ctx, app } = this
    const { id = '' } = ctx.query
    let user_id
    const token = ctx.request.header.authorization

    const decode = await app.jwt.verify(token, app.config.jwt.secret)

    if (!decode) return

    user_id = decode.id

    if (!id) {
      ctx.body = {
        code: 500,
        msg: '订单id不能为空',
      }
      return
    }
    try {
      const detail = await ctx.service.bill.detail(id, user_id)

      ctx.body = {
        code: 200,
        msg: '请求成功',
        data: detail,
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      }
    }
  }

  async update() {
    const { ctx, app } = this
    const {
      id,
      amount,
      type_id,
      type_name,
      date,
      pay_type,
      remark = '',
    } = ctx.request.body
    if (!amount || !type_id || !type_name || !date || !pay_type) {
      ctx.body = {
        code: 400,
        msg: '参数错误',
        data: null,
      }
    }

    try {
      let user_id
      const token = ctx.request.header.authorization

      const decode = await app.jwt.verify(token, app.config.jwt.secret)

      if (!decode) return
      user_id = decode.id

      const result = await ctx.service.bill.update({
        id, // 账单 id
        amount, // 金额
        type_id, // 消费类型 id
        type_name, // 消费类型名称
        date, // 日期
        pay_type, // 消费类型
        remark, // 备注
        user_id, // 用户 id
      })
      console.log(result)
      ctx.body = {
        code: 200,
        msg: '操作成功',
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      }
    }
  }

  async delete() {
    const { ctx, app } = this
    const { id } = ctx.request.body

    if (!id) {
      ctx.body = {
        code: 400,
        msg: '参数错误',
        data: null,
      }
    }
    try {
      let user_id
      const token = ctx.request.header.authorization
      const decode = await app.jwt.verify(token, app.config.jwt.secret)
      if (!decode) return
      user_id = decode.id

      const result = await ctx.service.bill.delete(id, user_id)
      console.log(result)
      ctx.body = {
        code: 200,
        msg: '请求成功',
        data: null,
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      }
    }
  }

  async data() {
    const { ctx, app } = this
    const { date = '' } = ctx.query

    try {
      let user_id
      const token = ctx.request.header.authorization
      const decode = await app.jwt.verify(token, app.config.jwt.secret)
      if (!decode) return
      user_id = decode.id

      const result = await ctx.service.bill.list(user_id)

      const start = dayjs(date).startOf('month').unix()
      const end = dayjs(date).endOf('month').unix()

      const _data = result.filter(
        (item) =>
          dayjs(item.date).unix() > start && dayjs(item.date).unix() < end,
      )

      const totalExpense = _data.reduce((arr, cur) => {
        if (cur.pay_type == 1) {
          arr += Number(cur.amount)
        }
        return arr
      }, 0)
      const totalIncome = _data.reduce((arr, cur) => {
        if (cur.pay_type == 2) {
          arr += Number(cur.amount)
        }
        return arr
      }, 0)
      console.log(totalIncome)

      let total_data = _data.reduce((arr, cur) => {
        const index = arr.findIndex((item) => item.type_id == cur.type_id)
        if (index == -1) {
          arr.push({
            type_id: cur.type_id,
            type_name: cur.type_name,
            pay_type: cur.pay_type,
            number: Number(cur.amount),
          })
        }
        if (index > -1) {
          arr[index].number = Number(cur.amount)
        }
        return arr
      }, [])

      total_data = total_data.map((item) => {
        console.log(item)
        item.number = Number(Number(item.number).toFixed(2))
        return item
      })

      ctx.body = {
        code: 200,
        msg: '请求成功',
        data: {
          total_expense: Number(totalExpense).toFixed(2),
          total_income: Number(totalIncome).toFixed(2),
          total_data: total_data || [],
        },
      }
    } catch (error) {
      console.log(error)
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      }
    }
  }
}

module.exports = BillController
